﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using AutoplanetaTaskManager.Models;

namespace AutoplanetaTaskManager.Daos.EntityFramework
{
    public class UserDao : IUserDao
    {
        public List<User> Load()
        {
            using (AtmDbEntities db = new AtmDbEntities())
            {
                return db.User.ToList();
            }
        }

        public List<User> LoadEmployees()
        {
            string roleName = "USER";
            using (AtmDbEntities db = new AtmDbEntities())
            {
                return (
                    from u in db.User
                    from r in db.Role
                    where u.RoleId == r.Id
                    where r.Name == roleName
                    select u).ToList();
            }
        }

        public User Get(int id)
        {
            using (AtmDbEntities db = new AtmDbEntities())
            {
                return db.User.FirstOrDefault(m => m.Id == id);
            }
        }

        public User Get(string userName, string password)
        {
            using (AtmDbEntities db = new AtmDbEntities())
            {
                return db.User.FirstOrDefault(m => m.UserName == userName && m.Password == password);
            }
        }

        public void Add(User user)
        {
            using (AtmDbEntities db = new AtmDbEntities())
            {
                db.AddToUser(user);
                db.SaveChanges();
            }
        }

        public void Update(User user)
        {
            using (AtmDbEntities db = new AtmDbEntities())
            {
                User record = db.User.FirstOrDefault(m => m.Id == user.Id);
                if (record != null)
                {
                    record.FirstName = user.FirstName;
                    record.LastName = user.LastName;
                    record.UserName = user.UserName;
                    record.Password = user.Password;
                }
                db.SaveChanges();
            }
        }

        public void Remove(int id)
        {
            using (AtmDbEntities db = new AtmDbEntities())
            {
                User user = db.User.FirstOrDefault(m => m.Id == id);
                if (user != null) db.DeleteObject(user);
                db.SaveChanges();
            }
        }
    }
}
